import Vue from 'vue'
import VueRouter from 'vue-router'

import Home from '@/views/Home/Home.vue'
import User from '@/views/User/User.vue'
import pathArr from '@/router/pathArr.js'
import Login from '@/views/MyLogin.vue'
import Register from '@/views/register.vue'
import Order from '@/views/Order/Order.vue'
Vue.use(VueRouter)

const router = new VueRouter({
  // 定义路由路径的
  routes: [
    // 第一个是重定向
    { path: '/', redirect: '/login' },
    { path: '/home', component: Home, meta: { isRecord: true, top: 0 } },
    { path: '/user', component: User },
    { path: '/login', component: Login },
    { path: '/order', component: Order },
    { path: '/register', component: Register }
  ],
  scrollBehavior(to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: to.meta.top || 0 }
    }
  }
})

// 全局前置守卫 判断token有没有的没有的话就不让进去
router.beforeEach(function(to, from, next) {
  if (pathArr.indexOf(to.path) !== -1) {
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
export default router
